package com.baizhi.controller;

import com.baizhi.entity.Product;
import com.baizhi.service.ProductService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
public class ProductController {
    @Autowired
    private ProductService productService;
    @Value("${imgPath}")
    private String path;
    @GetMapping("productes")
    public Map<String , Object> selectAll(int page,int limit){
        PageInfo<Product> pageInfo = productService.selectAll(page,limit);
        return new HashMap(){{
            put("code",0);
            put("msg","");
            put("data",pageInfo.getList());
            put("count",pageInfo.getTotal());
        }};
    }
    @DeleteMapping("productes")
    public void delete(@RequestBody List<Integer> bookList){
        for(Integer id : bookList){
            productService.delete(id);
        }
    }
    @PostMapping("productes")
    public void add(@RequestBody Product product){
        productService.add(product);
    }

    @PostMapping("/upload")
    public Map<String,Object> upload(MultipartFile file) throws IOException {
        String username = file.getOriginalFilename();
        String newName = UUID.randomUUID()+username;
        file.transferTo(new File(path,newName));
        return new HashMap(){{
            put("code",0);
            put("msg",newName);
        }};
    }
    @DeleteMapping("productes/{bookId}")
    public void deleteByid(@PathVariable("bookId") int bookId){
        productService.delete(bookId);
    }
    @GetMapping("productes/{bookId}")
    public Product selectByid(@PathVariable("bookId") int bookId){
        Product product = productService.selectById(bookId);
        return product;
    }
    @PutMapping("productes")
    public String updateByid(@RequestBody Product product){
        productService.update(product);
        return "ok";
    }
}
